//
//  ComposeViewController.swift
//  weibo1
//
//  Created by nick on 15/9/29.
//  Copyright © 2015年 nick. All rights reserved.
//

import UIKit
import SnapKit
class ComposeViewController: UIViewController {

    // 取消发送，返回
    @objc private func back() {
        // 先隐藏键盘，再销毁控制器，用户体验好
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    // 发送微博
    @objc private func sendStatus() {
        print("发送微博")
    }
    // 选择图片
    @objc private func selectPhoto() {
        print("选择图片")
    }
    // 工具条跟随键盘改变frame
    @objc private func keyboardFrameDidChanged(n: NSNotification) {
        // 传递进来的通知，包含键盘的状态属性
        /*
        NSConcreteNotification 0x7fb9baf482f0 {name = UIKeyboardDidChangeFrameNotification; userInfo = {
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
        UIKeyboardIsLocalUserInfoKey = 1;
        }}
        */
        print(n)
        // 取出键盘最后的frame
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        print(rect)
        // 取出动画时间
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        print(duration)
        // 根据键盘frame布局工具条的位置
        // 参照屏幕底部
        let screenHeight = UIScreen.mainScreen().bounds.height
        toolbar.snp_updateConstraints { (make) -> Void in
            // 屏幕左上角的点为{0,0}点
            make.bottom.equalTo(view.snp_bottom).offset(-screenHeight + rect.origin.y)
        }
        // 更新工具条的frame
        UIView.animateWithDuration(duration, animations: { () -> Void in
            self.view.layoutIfNeeded()
            }, completion: nil)
    }
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        
        prepareNavbar()
        prepareToolbar()
        prepareTextView()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // view和键盘一起加载，（显得比较突兀，用户体验不好）所以在viewDidAppear中让textView称为第一响应者
//        textView.becomeFirstResponder()
        // 添加通知监听键盘frame的变化
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameDidChanged:", name: UIKeyboardDidChangeFrameNotification, object: nil)
    }
    // 移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // view已经加载完成，再显示键盘（用户体验较好）
        textView.becomeFirstResponder()
    }
    // 添加textView
    private func prepareTextView() {
        //textView.becomeFirstResponder()
        // 添加输入框
        view.addSubview(textView)
        // 此属性设置textView不穿透导航条
        edgesForExtendedLayout = .None
        // 
        textView.addSubview(placeholderLabel)
        // 布局
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view.snp_top)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolbar.snp_top)
        }
        placeholderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    // 添加toolbar
    private func prepareToolbar() {
        // 添加
        view.addSubview(toolbar)
        toolbar.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        // 布局
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }
        // 3. 添加按钮
        let itemSettings = [["imageName": "compose_toolbar_picture", "actionName": "selectPhoto"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background"],
            ["imageName": "compose_addbutton_background"]]
        // 初始化一个数组，存放item
        var items = [UIBarButtonItem]()
        for dict in itemSettings {
            let imageName = dict["imageName"]!
            // 创建按钮 ,此方法里面根据图片的大小设置按钮的大小：sizetofit()所以不用设置frame
            let button = UIButton(imageName: imageName, bgImageName: nil)
            if let actionName = dict["actionName"] {
                button.addTarget(self, action: Selector(actionName), forControlEvents: UIControlEvents.TouchUpInside)
            }
            let item = UIBarButtonItem(customView: button)
            // 添加到数组
            items.append(item)
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolbar.items = items
    }
    
    // 添加导航条
    private func prepareNavbar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "back")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "sendStatus")
        // 设置发送按钮不可交互
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 添加导航标题view
        let navTitleView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
//        navTitleView.backgroundColor = UIColor.orangeColor()
        // 微博标题
        let weiboLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 18)
        // 标题用户名
        let userNameLabel = UILabel(title: "大刀哥威武的微博", color: UIColor.lightGrayColor(), fontSize: 15)
        // 添加控件
        navTitleView.addSubview(weiboLabel)
        navTitleView.addSubview(userNameLabel)
        // 布局
        weiboLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(navTitleView.snp_top)
            make.centerX.equalTo(navTitleView.snp_centerX)
        }
        userNameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(navTitleView.snp_centerX)
            make.bottom.equalTo(navTitleView.snp_bottom)
        }
        // 添加到导航条上
        navigationItem.titleView = navTitleView
    }
    // 懒加载控件
    // 输入文本
    private lazy var textView: UITextView = {
        let tv = UITextView()
        
        tv.textColor = UIColor.darkGrayColor()
        tv.font = UIFont.systemFontOfSize(18)
        // 设置textView可以垂直拖拽
        tv.alwaysBounceVertical = true
        // 设置textView拖拽隐藏键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
//        tv.text = "分享新鲜事..."
        tv.delegate = self
        return tv
    }()
    // toolbar
    private lazy var toolbar = UIToolbar()
    // 占为文本label
    private lazy var placeholderLabel: UILabel = UILabel(title: "分享新鲜事...", color: UIColor.darkGrayColor(), fontSize: 18)
}

extension ComposeViewController: UITextViewDelegate {
//    func textViewDidBeginEditing(textView: UITextView) {
//        self.placeholderLabel.removeFromSuperview()
//    }
//    func textViewShouldBeginEditing(textView: UITextView) -> Bool {
//        self.placeholderLabel.removeFromSuperview()
//        return true
//    }
    func textViewDidChange(textView: UITextView) {
        self.placeholderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
